package com.rd.p2p.auto_register.register;

import com.rd.p2p.auto_register.param.Users;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by gaoj on 2016/5/6.
 */
public class PostMd {

    public static void doPost(String POST_URL, List<Users> params) throws IOException {

        File csv = new File("");  //定义CSV文件的路径

        HttpClient client = new HttpClient();

        PostMethod post = new PostMethod(POST_URL);  //POST的URL

        //读取CSV文件中的数据
        try {
            BufferedReader reader = new BufferedReader(new FileReader(csv));
            reader.readLine();  //如果需要表头可以注释掉
            String line = null;
            while ((line = reader.readLine()) != null) {
                Users users = new Users();
                String[] param = line.split("\t");
                users.setUserName(param[0]);
                users.setMobilePhone(param[1]);
                users.setPwd(param[2]);
                users.setConfirmPassword(param[3]);
                users.setValidCode(param[4]);
                params.add(users);

                //发送Http请求
                try {
                    client.getHostConfiguration().setHost("localhost", 8080, "http");  //设置服务器地址和端口
                    //设置需要POST的参数
                    NameValuePair[] values = new NameValuePair[5];
                    values[0] = new NameValuePair("userName", users.getUserName());
                    values[1] = new NameValuePair("mobilePhone", users.getMobilePhone());
                    values[2] = new NameValuePair("pwd", users.getPwd());
                    values[3] = new NameValuePair("confirmPassword", users.getConfirmPassword());
                    values[4] = new NameValuePair("validCode", users.getValidCode());
                    post.addParameters(values);
                    client.executeMethod(post);  //发送请求
                } catch (HttpException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    post.releaseConnection();  //关闭连接
                }
            }
            reader.close();  //关闭reader，释放内存
            //请求Http需要的POST参数
            if (params != null) {
                for (Iterator<Users> it = params.iterator(); it.hasNext(); ) {
                    Users users = it.next();
                    System.out.println(users);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}